<?php

namespace app\admin\controller\scanwork;

use app\common\controller\Backend;
use think\Db;
use Exception;

/**
 * 库存盘点管理
 *
 * @icon fa fa-clipboard-check
 * @remark 管理库存盘点任务和结果
 */
class Stockinventory extends Backend
{
    /**
     * Stockinventory模型对象
     * @var \app\admin\model\scanwork\Stockinventory
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\scanwork\Stockinventory;
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['warehouse', 'creator'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $params['creator_id'] = $this->auth->id;
                $params['creator_name'] = $this->auth->username;
                $params['inventory_no'] = 'INV' . date('YmdHis') . mt_rand(1000, 9999);
                
                Db::startTrans();
                try {
                    $result = $this->model->allowField(true)->save($params);
                    if ($result !== false) {
                        Db::commit();
                        $this->success();
                    } else {
                        $this->error(__('No rows were inserted'));
                    }
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                Db::startTrans();
                try {
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        Db::commit();
                        $this->success();
                    } else {
                        $this->error(__('No rows were updated'));
                    }
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $item) {
                    $count += $item->delete();
                }
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 盘点明细
     */
    public function detail($inventory_id = null)
    {
        $inventory = $this->model->get($inventory_id);
        if (!$inventory) {
            $this->error(__('No Results were found'));
        }

        if ($this->request->isAjax()) {
            $details = Db::name('scanwork_stock_inventory_detail')
                ->alias('d')
                ->join('scanwork_material m', 'd.material_id = m.id')
                ->join('scanwork_location l', 'd.location_id = l.id', 'LEFT')
                ->where('d.inventory_id', $inventory_id)
                ->field('d.*, m.material_code, m.material_name, m.spec, m.unit, l.location_code, l.location_name')
                ->select();
            
            return json(['code' => 1, 'data' => $details]);
        }

        $this->view->assign('inventory', $inventory);
        return $this->view->fetch();
    }
}

